package com.atguigu.service.impl;

import com.atguigu.dao.OrderDao;
import com.atguigu.dao.OrderItemDao;
import com.atguigu.dao.impl.OrderDaoImpl;
import com.atguigu.dao.impl.OrderItemDaoImpl;
import com.atguigu.pojo.*;
import com.atguigu.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {

    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private OrderDao orderDao = new OrderDaoImpl();

    @Override
    public Order createOrder(CartItem cartItem, Integer userId) {
        // 订单号 唯一的
        String orderId = System.currentTimeMillis() + "" + userId;
        // 创建一个订单对象
        Order order = new Order(orderId, new Date(), cartItem.getTotalPrice(), 1, userId);;
        // 保存订单  记得先保存订单，然后再保存订单项，因为要先有订单再有订单项
        orderDao.saveOrder(order);
        // 遍历购物车中每一个商品项转换为订单项保存到数据库
        for(Map.Entry<Integer, Cart> entry: cartItem.getCartMap().entrySet()){
            // 将购物车每个商品转换为cart
            Cart cart = entry.getValue();

            // 保存订单项到数据库
            orderItemDao.saveOrderItem(new OrderItem(0, cart.getName(), cart.getCount(), cart.getPrice(), cart.getTotalPrice(), orderId));
        }
        // 清空购物车 因为结算肯定把购物车清空了
        cartItem.clear();
        // 返回订单信息
        return order;
    }

    @Override
    public List<Order> queryOrdersAll() {
        return orderDao.queryOrdersAll();
    }

    @Override
    public List<Order> queryOrdersById(int userId) {
        return orderDao.queryOrdersById(userId);
    }

    @Override
    public void deleteOrderById(String order_id) {
        orderDao.deleteOrderById(order_id);
    }
}
